// -----------lang.js-----------------------
function importJavascript(url, success) {
    if (!success) {
        success = function() {
        };
    }
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.src = url;
    var done = false;

    script.onload = script.onreadystatechange = function() {
        if (!done && ready(this)) {
            done = true;
            success();
        }
    };
    head.appendChild(script);
}

function ready(script) {
    return !script.readyState || script.readyState == 'loaded' || script.readyState == 'complete';
}

function log(someValue) {
    if (typeof console != "undefined") {
        console.log(someValue)
    } else {
        alert(someValue);
    }
}
function logAll(name, someObject) {
    log("logAll: " + name);
    for (i in someObject) {
        log(i + " => " + someObject[i]);
    }
}

function logAllRecursive(name, someObject) {
    log("logAll: " + name);
    for (i in someObject) {
        logAll(someObject[i]);
    }
}

// ----------- End lang.js-----------------------

// Log results as HTML on the page
var trivialReporter = new jasmine.TrivialReporter();
jasmine.getEnv().addReporter(trivialReporter);

// Log results as JSON
var ourReporter = new jasmine.JsApiReporter();
jasmine.getEnv().addReporter(ourReporter);

var indent = function(indentLevel) {
    var indent = '';
    for (var i = 0; i < indentLevel; i++) {
        indent += ' ';
    }
    return indent;
};

var buildMessages = function(messages, indentLevel) {
    var message = '';
    for (var i = 0; i < messages.length; i++) {
        message += '\n' + indent(indentLevel) + ' * ' + messages[i].message;
    }
    return message;
};

var buildReport = function(items, indentLevel) {
    var report = '';
    for (var i = 0; i < items.length; i++) {
        var item = items[i];
        report += "\n" + indent(indentLevel) + (item.type == 'suite' ? 'describe ' : 'it ') + item.name;

        if (item.type == 'spec') {
            var result = ourReporter.results()[item.id];
            if (result.result == 'failed') {
                report += ' <<< FAILURE!';
                report += buildMessages(result.messages, indentLevel + 1);
            }
        }
        report += ' ' + buildReport(item.children, indentLevel + 1);
    }
    return report;
};

var run = function() {
    jasmine.getEnv().execute();
};

var report = function() {
    return buildReport(ourReporter.suites(), 0);
};

